package com.mybatispuls.springboot.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.mybatispuls.springboot.service.OssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.joda.time.DateTime;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uplotdfile(MultipartFile multipartFile) {
// Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = "LTAI4GFHKf74Y14gAATonWdQ";
        String accessKeySecret = "ZP2o7qKto6K7gTGjbzIOUk60HocBdi";
        String bucketName = "yang3413";

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String filename = multipartFile.getOriginalFilename();
            //文件名加上随机唯一的值，使文件名不重复
            String uuid = UUID.randomUUID().toString().substring(0,6).replaceAll("-", "");

            String time = new DateTime().toString("yyyy/MM/dd");
            filename = time+"/"+uuid+filename;
            // 上传文件流。
            InputStream inputStream = multipartFile.getInputStream();
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            //https://yang3413.oss-cn-beijing.aliyuncs.com/user.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        }catch (Exception e){
            return null;
        }

    }
}
